/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wzhq.pacsai;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wzhq.commTencent.PostDcm;
import com.wzhq.commTencent.PostTencent;
import com.wzhq.commTencent.ReceiveReport;
import com.wzhq.model.MainImages;
import com.wzhq.model.Ris.ExamInfo;
import com.wzhq.model.Ris.SyncAIStatus;
import static com.wzhq.pacsai.MainConfig.configPlugin;
import com.wzhq.util.JsfUtil;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GG
 */
public class HisPacsInter implements Runnable {

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(HisPacsInter.class);
    String jobName;
    int allCounts = 0;

    public HisPacsInter(String jobName) {
        this.jobName = jobName;
    }

    //从服务器取报告
    public String syncRISHIS() {
        boolean isSuccess = true;
        String ExamItemHISID = null;
        String StudyInstanceUID = null;
        String MPPSID = null;

        //使用RIS中SyncAIStatus触发表关连ExamInfo中的ExamID查到HIS中的检查号，通过检查号查到所需信息，对照上传类型后写入AI库同步表中
        String sql = "SELECT a.StudyInstanceUID,b.ExamItemHISID,b.PreExamNotes,b.spare6,a.MPPSID FROM "
                + "SyncAIStatus a INNER JOIN ExamInfo b ON a.ExamID=b.ExamID and a.SyncFlag=0  order by a.SyncTime LIMIT 100";
        List<ExamInfo> syncAIStatusRis = ExamInfo.dao.use("mysqlRis").find(sql);
        if ((syncAIStatusRis == null) || (syncAIStatusRis.isEmpty())) {
            //无新图像
            return "RIS中无新的图像！";
        } else {
            try {
                for (int j = 0; j < syncAIStatusRis.size(); j++) {
                    if (syncAIStatusRis.get(j).getStr("ExamItemHISID") == null || syncAIStatusRis.get(j).getStr("ExamItemHISID").isEmpty()) {
                        //RIS中没有HIS申请号，可能是RIS手工登记 ,直接跳过
                    } else {
                        ExamItemHISID = syncAIStatusRis.get(j).getStr("ExamItemHISID");
                        StudyInstanceUID = syncAIStatusRis.get(j).getStr("StudyInstanceUID");
                        MPPSID = syncAIStatusRis.get(j).getStr("MPPSID");

                        //置同步记录
                        Record syncAIStatusLock = Db.use("mysqlRis").findById("SyncAIStatus", "MPPSID", MPPSID).set("SyncFlag", 1).set("SyncTime", JsfUtil.getDateTime());
                        Db.use("mysqlRis").update("SyncAIStatus", "MPPSID", syncAIStatusLock);

                        //根据RIS中的检查号查找HIS记录
                        List<Record> examMasterHIS = Db.use("oracle").find("select a.patient_id,a.exam_no,a.name,b.exam_item,a.exam_date_time,a.sex,a.date_of_birth,b.exam_item_code"
                                + " from exam_master a,exam_items b where a.exam_no= b.exam_no  and a.exam_no=?", ExamItemHISID);
                        if ((examMasterHIS == null) || (examMasterHIS.isEmpty())) {
                            //无新图像
                            return "HIS查无此人！";
                        } else {
                            String patient_id = examMasterHIS.get(0).getStr("patient_id");
                            String exam_no = examMasterHIS.get(0).getStr("exam_no");
                            String exam_item = examMasterHIS.get(0).getStr("exam_item");
                            String exam_date_time = examMasterHIS.get(0).getStr("exam_date_time");
                            String name = examMasterHIS.get(0).getStr("name");
                            String exam_item_code = examMasterHIS.get(0).getStr("exam_item_code");
                            //对照表查接口接收代码
                            Record AiRisHisDict = Db.findById("select AiStudyTypeCode from AiRisHisDict  where  RisHisCode=? and UsingFlag=1 ", exam_item_code);
                            if ((AiRisHisDict == null)) {
                                //不符合病种要求的记录 ,直接跳过
                            } else {
                                allCounts++;
                                String studyType = AiRisHisDict.getStr("AiStudyTypeCode");
                                Record su = Db.findById("syncAIStatus", "StudyInstanceUID", StudyInstanceUID);
                                Record syncAIStatus = new Record().set("StudyInstanceUID", StudyInstanceUID).set("ExamNo", ExamItemHISID).set("EnterTime", JsfUtil.getDateTime()).
                                        set("StudyName", exam_item).set("StudyDate", exam_date_time).set("StudyType", studyType).set("PatientName", name).set("PatientId", patient_id);
                                if (su == null) {
                                    Db.save("syncAIStatus", "StudyInstanceUID", syncAIStatus);
                                } else {
                                    Db.update("syncAIStatus", "StudyInstanceUID", syncAIStatus);
                                }

                            }
                        }
                    }
                }
            } catch (Exception e) {
                isSuccess = false;
                PostTencent.ERRPOSTOPERFLAG = 1;
                LOG.error("从RIS中取待同步记录出错！");
                LOG.error(e.toString());
                e.printStackTrace();
            }
            return isSuccess ? "从RIS中取得的新记录条数：" + allCounts : "出现系统错误！" + StudyInstanceUID;
        }
    }

    public static void main(String[] args) {
        configPlugin();
        // syncRISHIS();
    }

    @Override
    public void run() {
        String Message = "正常";
        System.out.println(jobName + " 启动：" + Calendar.getInstance().get(Calendar.SECOND));
        try {
            Message = this.syncRISHIS();
        } catch (Exception ex) {
            Message = "该进程出现错误！";
            LOG.error("从服务器取报告错误:");
            LOG.error(ex.toString());
            Logger.getLogger(ReceiveReport.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Thread.sleep(2000);
        System.out.println(jobName + " 退出，结果：" + Message + "||||||" + Calendar.getInstance().get(Calendar.SECOND));
    }
}
